<template>
  <div>

    <el-button class="button-container" type="success" @click="updateUpload() ;">提 交</el-button>

    <el-upload
        ref="uploadFileRef"
        class="avatar-uploader"
        :action="'http://localhost:6301/file'"
        :file-list="fileList"
        :auto-upload="false"
        :show-file-list="true"
        multiple
        drag
        :before-upload="beforeUpload"
        :limit="5"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        Drop file here or <em>click to upload</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          最多选择5张 jpg/png/jpeg 格式文件
        </div>
      </template>
    </el-upload>


  </div>


</template>

<script setup>
import {ref} from 'vue'
import {UploadFilled} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

let fileList = ref([])
const uploadFileRef = ref([])

// 文件上传之前执行
const beforeUpload = (file) => {
  // 限制文件大小 < 4MB
  const maxSize = 4 * 1024 * 1024;
  if (file.size > maxSize) {
    message("info","文件过大")
    return false;
  }
  return true;
};

// 超出文件上限时提示
const handleExceed = (files, fileList) => {
  message("info","超出上传数量限制")
  return false
};

// 上传文件
const updateUpload = () => {
  uploadFileRef.value.submit() // submit 触发 action 对应的接口
  fileList.value = []
}

// 处理上传成功的回调函数
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    message("success","上传文件成功:【" + response.data + "】")
  } else {
    message("info", "上传文件失败:【" + response.data + "】")
  }
};

// 处理上传失败的回调函数
const handleUploadError = (error, file, fileList) => {
  message("info", "上传文件失败")
};

// 消息提示
function message(type, msg) {
  ElMessage({
    type: type,
    message: msg,
  })
}


</script>

<style scoped>
.button-container {
  margin: 20px 43%;
}
</style>
